import 'dart:math';

import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/ui/app_main.dart';
import 'package:e_reception_flutter/ui/index/bean/index_bind_termainal_info.dart';
import 'package:e_reception_flutter/ui/new_terminal/binding_terminal/terminal_detail_info_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/new_terminal_list/bean/common_terminal_settings_response_bean.dart';
import 'package:e_reception_flutter/ui/new_terminal/set_terminal_volume_dialog.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/terminal_detail_page.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/terminal_detail_view_model.dart';
import 'package:e_reception_flutter/ui/new_terminal/terminal_detail/widgets/operation_success_tips_dialog.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';
import 'package:vg_base/vg_screen_lib.dart';
import 'package:vg_base/vg_string_util_lib.dart';
import 'package:vg_flutter_base_moudle/vg_moudle_widget_lib.dart';

import '../index_page.dart';

/// 首页-网络终端展示
///
/// @author: zengxiangxi
/// @createTime: 1/5/21 5:55 PM
/// @specialDemand:
class IndexGridTerminalWidget extends StatefulWidget {
  final List<NewBindTerminalListBean> list;
  final int selectIndex;
  final Function(int index) onSelect;
  final Function(String hsn) cancelRepeat;
  final ValueNotifier<int> selectValue;
  final Function(String hsn, String onOff, int volume) setVolume;
  final Function(bool status, String hsn, int rcaid, String terminalName, ComAutoSwitchBean autoBean) onOff;
  final bool lightTheme;

  const IndexGridTerminalWidget({Key key, this.list, this.selectIndex,
    this.onSelect, this.cancelRepeat, this.selectValue, this.setVolume, this.onOff, this.lightTheme})
      : super(key: key);


  @override
  State<StatefulWidget> createState() {
    return new IndexGridTerminalWidgetState();
  }

}

class IndexGridTerminalWidgetState extends BaseState<IndexGridTerminalWidget> {
  int _selectIndex;
  double _itemWidth;
  Stream<double> _stream;
  double _opacityLevel = 1.0;
  ValueNotifier<double> _opacityLevelValueNotifier;
  @override
  void initState() {
    _selectIndex  = widget?.selectIndex;
    super.initState();
    _opacityLevelValueNotifier = new ValueNotifier(1.0);
    _stream = Stream.periodic(Duration(milliseconds: 500), (value){
      _opacityLevel = _opacityLevel == 0 ? 1.0 : 0.0;
      return _opacityLevel;
    });

    _stream.listen((event) {
      _opacityLevelValueNotifier.value = event;
    });
    // widget?.initSelectIndex = (index){
    //   setState(() {
    //     _selectIndex = index;
    //   });
    // };
  }
  @override
  Widget build(BuildContext context) {
    _itemWidth = (ScreenUtils.screenW(context) - 15 - 16)/2.5;
    return GridView.builder(
        padding: EdgeInsets.only(
          left: 15, right: 15,),
        itemCount: widget?.list?.length ?? 0,
        physics: BouncingScrollPhysics(),
        scrollDirection: Axis.horizontal,
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 1,
            mainAxisSpacing: 8,
            crossAxisSpacing: 0,
            childAspectRatio: (_itemWidth + 12)/_itemWidth
        ),
        itemBuilder: (BuildContext context, int index) {
          return _toNewGridItemWidget(context, widget?.list?.elementAt(index), index);
        });

  }

  Widget _toNewGridItemWidget(
      BuildContext context, NewBindTerminalListBean itemBean, int index) {
    Color selectedBorderColor = (widget?.lightTheme??false)?Color(0XFF1890FF):Color(0XFF00CBFF);
    String selectedAsset = (widget?.lightTheme??false)?"images/icon_terminal_selected_light.png":"images/icon_terminal_selected.png";
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      onTap: () {
        if(_selectIndex != index){
          _selectIndex = index;
          if(widget?.onSelect != null) {
            widget?.onSelect(_selectIndex);
          }
          widget.selectValue.value = _selectIndex;
          setState(() {

          });
        }else{
          TerminalDetailInfoPage.navigatorPush(context, itemBean?.hsn, router: AppMain.ROUTER);
        }
      },
      child: Column(
        children: <Widget>[
          Container(
            height: _itemWidth,
            width: _itemWidth,
            foregroundDecoration: BoxDecoration(
              border: Border.all(
                  color: index == _selectIndex?selectedBorderColor:Colors.transparent,
                  width: index == _selectIndex? 1:0),
              borderRadius: BorderRadius.circular(12),
            ),
            child: ClipRRect(
              borderRadius: BorderRadius.circular(12),
              child: Stack(
//                fit: StackFit.expand,
                children: <Widget>[
                  _toBgImageWidget(itemBean, _itemWidth, widget?.lightTheme),
                  Container(
                    child: TerminalGradientColorWidget(itemBean.terminalPicurl, _itemWidth, widget?.lightTheme),
                  ),
                  Align(
                      alignment: Alignment.bottomCenter,
                      child: _toStatisticsColumnWidget(itemBean)),
                  Align(
                    alignment: Alignment.center,
                    child: GestureDetector(
                        behavior: HitTestBehavior.opaque,
                        onTap: (){
                          VgEventBus.global.send(new UpdateHomePageEventMonitor());
                          if(itemBean.getTerminalIsOff() || ("01" != itemBean?.stopflg??"")){
                            if(_selectIndex != index){
                              _selectIndex = index;
                              if(widget?.onSelect != null) {
                                widget?.onSelect(_selectIndex);
                              }
                              widget.selectValue.value = _selectIndex;
                              setState(() {

                              });
                            }else{
                              TerminalDetailInfoPage.navigatorPush(context, itemBean?.hsn, router: AppMain.ROUTER);
                            }
                            return;
                          }
                          if(widget?.lightTheme??false){
                            return;
                          }
                          if(itemBean.getTerminalIsOff()){
                            OperationSuccessTipsDialog.navigatorPushDialog(context, title: "设备已关机，无法设置重复播放");
                            return;
                          }
                          if(widget?.cancelRepeat != null) {
                            widget?.cancelRepeat(itemBean.hsn);
                          }
                        },
                        child: Container(
                          width: 40,
                          height: 40,
                          child: _toRepeatWidget(itemBean),
                        )
                    ),
                  ),

                  Positioned(
                    top: 7,
                    left: 7,
                    child: GestureDetector(
                        behavior: HitTestBehavior.translucent,
                        onTap: (){
                          if(widget?.onOff != null){
                            widget?.onOff?.call(itemBean?.getTerminalIsOff(),
                                itemBean?.hsn, itemBean?.rcaid, itemBean?.getTerminalName(),
                                itemBean?.comAutoSwitch);
                          }
                        },
                        child: Container(
                          width: 60,
                          height: 40,
                          alignment: Alignment.topLeft,
                          child: _toOnOffWidget(itemBean),
                        )
                    ),
                  ),
                  Visibility(
                    visible: !(itemBean?.getTerminalIsOff()??true),
                    child: Positioned(
                      top: 7,
                      right: 7,
                      child: GestureDetector(
                          behavior: HitTestBehavior.translucent,
                          onTap: (){
                            VgEventBus.global.send(new UpdateHomePageEventMonitor());
                            SetTerminalVolumeDialog.navigatorPushDialog(context, itemBean.soundonoff, itemBean.hsn, itemBean.volume);
                            // if(widget?.setVolume != null) {
                            //   widget?.setVolume(
                            //       itemBean.hsn,
                            //       ("00" == itemBean.soundonoff??"")?"01":"00",
                            //       itemBean.volume,
                            //   );
                            // }
                          },
                          child: Container(
                            width: 30,
                            height: 30,
                            alignment: Alignment.topRight,
                            child: _toVolumeWidget(itemBean),
                          )
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ),
          SizedBox(height: 5,),
          // Visibility(
          //   visible: index == _selectIndex,
          //   child: Image(
          //     image: AssetImage("images/icon_terminal_selected.png"),
          //     width: 14,
          //     height: 7,
          //   ),
          // ),
          ValueListenableBuilder(
            valueListenable: widget?.selectValue,
            builder: (BuildContext context, int changedIndex, Widget child){
              _selectIndex = changedIndex;
              return Visibility(
                visible: index == _selectIndex,
                child: Image(
                  image: AssetImage(selectedAsset),
                  width: 14,
                  height: 7,
                ),
              );
            },
          ),

        ],
      ),

    );
  }

  Widget _toRepeatWidget(NewBindTerminalListBean itemBean){
    if(widget?.lightTheme??false){
      return Container();
    }
    return (("01" == itemBean?.stopflg??"") && !itemBean.getTerminalIsOff())?
    ValueListenableBuilder(
        valueListenable: _opacityLevelValueNotifier,
        builder: (BuildContext context, double opacityLevel, Widget child){
          return AnimatedOpacity(
            opacity: opacityLevel,
            duration: Duration(milliseconds: 500),
            curve: Curves.linear,
            child: Container(
              child: Image.asset(
                "images/icon_repeat.png",
                width: 20,
                height: 20,
              ),
            ),
          );
        }
    ):Container();
  }

  Widget _toVolumeWidget(NewBindTerminalListBean itemBean){
    return Image.asset(
      (("01" == itemBean.soundonoff??"") || (0 == itemBean?.volume))?"images/icon_voice_0.png":"images/icon_voice_1.png",
      width: 20,
      height: 20,
    );
  }

  Widget _toOnOffWidget(NewBindTerminalListBean itemBean){
    String onAsset = (widget?.lightTheme??false)?"images/icon_terminal_on_light_theme.png":"images/icon_terminal_on.png";
    String offAsset = (widget?.lightTheme??false)?"images/icon_terminal_off_light_theme.png":"images/icon_terminal_off.png";
    return Image.asset(
      (itemBean?.getTerminalIsOff()??true)?offAsset:onAsset,
      width: 60,
    );
  }

}



Widget _toBgImageWidget(NewBindTerminalListBean itemBean, double itemWidth, bool lightTheme) {
  return TerminalGradientColorWidget(itemBean?.terminalPicurl, itemWidth, lightTheme);
}

Widget TerminalGradientColorWidget(String terminalPicurl, double itemWidth, bool lightTheme){
  return Stack(
    fit: StackFit.expand,
    children: <Widget>[
      Container(
        color: (lightTheme??false)?Color(0xFFD0E0F7):Color(0xFF191E31),
        child: VgCacheNetWorkImage(
          terminalPicurl??"",
          fit: BoxFit.cover,
          imageQualityType: ImageQualityType.middleDown,
//            errorWidget: Container(color: Color(0xFF191E31),),
//            placeWidget: Container(color: Color(0xFF191E31),),
          errorWidget: Container(
            padding: EdgeInsets.only(left: 32, top: 25, right: 32, bottom: 39),
            child: Image.asset(
              (lightTheme??false)?"images/icon_terminal_holder_light.png":"images/icon_terminal_holder.png",
              width: itemWidth-2*37,
              height: itemWidth-2*32,
              fit: BoxFit.cover,
            ),
          ),
          placeWidget: Container(
            padding: EdgeInsets.only(left: 32, top: 25, right: 32, bottom: 39),
            child: Image.asset(
              (lightTheme??false)?"images/icon_terminal_holder_light.png":"images/termial_empty_place_holder_ico.png",
              width: itemWidth-2*37,
              height: itemWidth-2*32,
              fit: BoxFit.cover,
            ),
          ),
        ),
      ),
      Container(
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [
//                Color(0xFF191E31),
              Colors.black.withOpacity(0.0),
              Colors.black.withOpacity(0.0),
              Colors.black.withOpacity(0.0),
              Colors.black.withOpacity(0.0),
              Colors.black.withOpacity(0.0),
              Colors.black.withOpacity(0.1),
              Colors.black.withOpacity(0.5),
              Colors.black.withOpacity(0.6),
//                Colors.black.withOpacity(0.7),
            ],
          ),
        ),
      ),
    ],
  );
}

Widget _toStatisticsColumnWidget(NewBindTerminalListBean itemBean) {
  return Container(
    margin: const EdgeInsets.only(left:10, right: 10, top: 8, bottom: 8),
    alignment: Alignment.bottomLeft,
    child: Row(
      children: [
        Visibility(
          visible: (StringUtils.isEmpty(itemBean?.terminalName) && StringUtils.isEmpty(itemBean?.sideNumber)&& StringUtils.isNotEmpty(itemBean?.hsn)),
          child: Text(
            // "硬件ID：",
            "",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color:
              ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
              fontSize: 15,
              fontWeight: FontWeight.w600,
              // fontWeight: FontWeight.w600
            ),
          ),
        ),
        Expanded(
          child: Text(
            "${itemBean?.getTerminalName() ?? ""}",
            maxLines: 1,
            overflow: TextOverflow.ellipsis,
            style: TextStyle(
              color:
              ThemeRepository.getInstance().getTextMainColor_D0E0F7(),
              fontSize: 15,
              fontWeight: FontWeight.w600,
            ),
          ),
        ),
      ],
    ),
  );
}
